package com.example.weight.wormHandle.garbageDisposal.onsiteDispose;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Locale;
import java.util.Map;

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.weight.R;
import com.example.weight.config.Config;
import com.example.weight.util.WeightActivity;
import com.hjq.bar.OnTitleBarListener;
import com.hjq.bar.TitleBar;

import org.json.JSONException;
import org.json.JSONObject;

public class WormOutcoming extends AppCompatActivity implements View.OnClickListener{
    private String name, factory;
    private TextView incoming_date;
    private TextView outcoming_date;
    private TextView worm_outcoming_insectDung;
    private TextView worm_outcoming_insect;
    private TextView cabinetNumber;
    private TextView layerNumber;
    private EditText remark;
    private String recordid = null;

    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");// HH:mm:ss

    long timedata = System.currentTimeMillis();
    Date outcomingDate = new Date(timedata);
    Date incomingDate = new Date(timedata-604800000L);

    String activeButton = new String();
    DateFormat format= DateFormat.getDateTimeInstance();
    Calendar calendar= Calendar.getInstance(Locale.CHINA);
    private TitleBar titleBar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.worm_outcoming);

        Intent previousIntent = getIntent();
        name = previousIntent.getStringExtra("name");
        factory = previousIntent.getStringExtra("factory");

        titleBar=findViewById(R.id.titleBar);
        titleBar.setOnTitleBarListener(new OnTitleBarListener() {

            @Override
            public void onLeftClick(View v) {
                WormOutcoming.this.finish();
            }

            @Override
            public void onTitleClick(View v) {
            }
            @Override
            public void onRightClick(View v) {
            }
        });
        incoming_date = (TextView) findViewById(R.id.worm_outcoming_incomingDate);
//        incoming_date.setOnClickListener(this);
        outcoming_date = (TextView) findViewById(R.id.worm_outcoming_outcomingDate);
        outcoming_date.setOnClickListener(this);
        /**
         *2个重量
         */
        //虫粪
        worm_outcoming_insectDung = findViewById(R.id.worm_outcoming_insectDung);
        //虫
        worm_outcoming_insect = findViewById(R.id.worm_outcoming_insect);

        cabinetNumber = findViewById(R.id.worm_outcoming_cabinet);
        layerNumber = findViewById(R.id.worm_outcoming_layer);
        remark = findViewById(R.id.worm_outcoming_remark);
        incoming_date.setText(simpleDateFormat.format(incomingDate));
        outcoming_date.setText(simpleDateFormat.format(outcomingDate));
        getdis();

        //获取当天最新一条数据
//        RequestQueue queue = Volley.newRequestQueue(this);
//        String url = Config.url + "/kitchenwaste/discharge/getlast" + "?factory=" + factory;
//        StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
//                new Response.Listener<String>() {
//                    @Override
//                    public void onResponse(String response) {
//                        try {
//                            JSONObject jsonObject = new JSONObject(response);
//                            Log.d("jy",response.toString());
//                            JSONObject data;
//                            if(jsonObject.get("data")!=null && !jsonObject.get("data").toString().equals("null")){
//                                data = jsonObject.getJSONObject("data");
//                                if (!data.isNull("id")
////                                        && data.getString("factory").equals(factory)
//                                ) {
//                                    incoming_date.setText(data.getString("incomeDate"));
//                                    outcoming_date.setText(data.getString("dischargeDate"));
//                                    worm_outcoming_insectDung.setText(data.getString("insectDungWeight"));
//                                    worm_outcoming_insect.setText(data.getString("insectWeight"));
//                                    cabinetNumber.setText(data.getString("cabinetNumber"));
//                                    layerNumber.setText(data.getString("layerNumber"));
//                                    remark.setText(data.getString("remark"));
//                                    Toast.makeText(WormOutcoming.this,
//                                            "今日已填写此表", Toast.LENGTH_SHORT).show();
//                                }
//                            }else{
//                                incoming_date.setText(simpleDateFormat.format(incomingDate));
//                                outcoming_date.setText(simpleDateFormat.format(outcomingDate));
//                            }
//                        } catch (JSONException e) {
//                            e.printStackTrace();
//                        }
//                    }
//                }, new Response.ErrorListener() {
//            @Override
//            public void onErrorResponse(VolleyError error) {
//                Toast.makeText(WormOutcoming.this,
//                        "获取信息失败 " + error.getMessage(), Toast.LENGTH_SHORT).show();
//            }
//        });
//        stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
//                DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
//        queue.add(stringRequest);
    }
    /**
     * 日期选择
     * @param activity
     * @param themeResId
     * @param tv_out
     * @param calendar
     */
    public void showDatePickerDialog(Activity activity, int themeResId, final TextView tv_out,final TextView tv_in, Calendar calendar,SimpleDateFormat simpleDateFormat) {
        // 直接创建一个DatePickerDialog对话框实例，并将它显示出来
        new DatePickerDialog(activity, themeResId, new DatePickerDialog.OnDateSetListener() {
            // 绑定监听器(How the parent is notified that the date is set.)
            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                // 此处得到选择的时间，可以进行你想要的操作
                tv_out.setText(new StringBuilder()
                        .append(year)
                        .append("-")
                        .append((monthOfYear + 1) < 10 ? "0"+ (monthOfYear + 1) : (monthOfYear + 1))
                        .append("-")
                        .append((dayOfMonth < 10) ? "0" + dayOfMonth : dayOfMonth));
//                根据出料日期修改进料日期
                changeDate(tv_out,tv_in,calendar,simpleDateFormat);
//                try {
////                    修改进料日期
//                    calendar.setTime(simpleDateFormat.parse(tv_out.getText().toString()));
//                    Date incomeDate = new Date(calendar.getTimeInMillis()-604800000L);
//                    tv_in.setText(simpleDateFormat.format(incomeDate));
//                } catch (ParseException e) {
//                    e.printStackTrace();
//                }
//                查询出料日期是否有对应出柜号和出料层数
            }
        }
                // 设置初始日期
                , calendar.get(Calendar.YEAR)
                , calendar.get(Calendar.MONTH)
                , calendar.get(Calendar.DAY_OF_MONTH)).show();

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.worm_outcoming_outcomingDate:
                showDatePickerDialog(this,  2, outcoming_date, incoming_date,calendar,simpleDateFormat);
                break;
            default:
                break;
        }
    }

    /**
     * 称重接口
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        String weight = data.getStringExtra("weight");
        switch (activeButton){
            case "worm_outcoming_insectDung_btn":
                worm_outcoming_insectDung.setText(weight);
                break;
            case "worm_outcoming_insect_btn":
                worm_outcoming_insect.setText(weight);
                break;
        }
    }

    public void goWeight(View view) {
        switch (view.getId()) {
            case R.id.worm_outcoming_insectDung_btn:
                activeButton = "worm_outcoming_insectDung_btn";
                break;
            case R.id.worm_outcoming_insect_btn:
                activeButton = "worm_outcoming_insect_btn";
                break;
            default:
                break;
        }
        Intent intent = new Intent(WormOutcoming.this, WeightActivity.class);
        startActivityForResult(intent, 1);
    }

    public void save(View view) {
        if (outcoming_date.getText().toString().equals("")) {
            Toast.makeText(this, "请填写粉碎开始时间", Toast.LENGTH_SHORT).show();
            return;
        }
        if (incoming_date.getText().toString().equals("")) {
            Toast.makeText(this, "请填写粉碎结束时间", Toast.LENGTH_SHORT).show();
            return;
        }
        if (worm_outcoming_insectDung.getText().toString().equals("")) {
            Toast.makeText(this, "请填写虫沙重量", Toast.LENGTH_SHORT).show();
            return;
        }
        if (worm_outcoming_insect.getText().toString().equals("")) {
            Toast.makeText(this, "请填写虫重", Toast.LENGTH_SHORT).show();
            return;
        }
        new AlertDialog.Builder(this)
                .setTitle("确定保存吗？")
                .setCancelable(false)
                .setNegativeButton("取消", ((dialog, which) ->
                        Toast.makeText(this, "取消保存", Toast.LENGTH_SHORT).show()))
                .setPositiveButton("确定", (dialog, which) -> {
                    if (recordid == null) {
                        Toast.makeText(this, "请正确填写/提交柜号及出料层数", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    //提交请求
                    RequestQueue queue = Volley.newRequestQueue(this);
                    String url = Config.url + "/kitchenwaste/discharge/addsecond";
//                    String url = Config.url + "/kitchenwaste/discharge/add";
                    StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                        new Response.Listener<String>() {
                            @Override
                            public void onResponse(String response) {
                                Log.d("jy", response);
                                try {
                                    JSONObject jsonObject = new JSONObject(response);
                                    String data = jsonObject.getString("data");
                                    if (data.equals("1")) {
                                        recordid = null;
                                        Toast.makeText(WormOutcoming.this,
                                                "保存成功", Toast.LENGTH_SHORT).show();
                                    }else
                                        Toast.makeText(WormOutcoming.this,
                                            "保存失败", Toast.LENGTH_SHORT).show();
                                } catch (JSONException e) {
                                    Toast.makeText(WormOutcoming.this,
                                            "保存失败", Toast.LENGTH_SHORT).show();
                                    e.printStackTrace();
                                }
                            }
                        }, new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            Toast.makeText(WormOutcoming.this, "保存失败2", Toast.LENGTH_SHORT).show();
                        }
                    }) {
                        @Override
                        protected Map<String, String> getParams() throws AuthFailureError {
                            Map<String, String> map=new HashMap<>();
                            map.put("id", recordid);
                            map.put("insectDungWeight", worm_outcoming_insectDung.getText().toString());
                            map.put("insectWeight", worm_outcoming_insect.getText().toString());
                            map.put("remark",remark.getText().toString());
                            map.put("recorder",name);
                            map.put("factory",factory);
                            return map;
                        }
                    };
                    stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                            DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
                    queue.add(stringRequest);
                })
                .show();
    }

    public void addTime(View view){
        if ( cabinetNumber.getText().toString().equals("")) {
            Toast.makeText(this, "请填写柜号", Toast.LENGTH_SHORT).show();
            return;
        }
        if ( layerNumber.getText().toString().equals("")) {
            Toast.makeText(this, "请填写出料层数", Toast.LENGTH_SHORT).show();
            return;
        }
        new AlertDialog.Builder(this)
                .setTitle("确定保存吗？")
                .setCancelable(false)
                .setNegativeButton("取消", ((dialog, which) ->
                        Toast.makeText(this, "取消保存", Toast.LENGTH_SHORT).show()))
                .setPositiveButton("确定", (dialog, which) -> {
                    //提交请求
                    RequestQueue queue = Volley.newRequestQueue(this);
                    String url = Config.url + "/kitchenwaste/discharge/addtime";
                    StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                            new Response.Listener<String>() {
                                @Override
                                public void onResponse(String response) {
                                    Log.d("jy", response);
                                    try {
                                        JSONObject jsonObject = new JSONObject(response);
                                        String data = jsonObject.getString("data");
                                        if (data.equals("true")) {
    //                                        清空
                                            outcoming_date.setText(simpleDateFormat.format(outcomingDate));
                                            changeDate(outcoming_date,incoming_date,calendar,simpleDateFormat);
                                            cabinetNumber.setText("");
                                            layerNumber.setText("");
                                            Toast.makeText(WormOutcoming.this, "提交成功", Toast.LENGTH_SHORT).show();
                                        }
                                    } catch (JSONException e) {
                                        Toast.makeText(WormOutcoming.this,
                                                "保存失败", Toast.LENGTH_SHORT).show();
                                        e.printStackTrace();
                                    }
                                }
                            }, new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            Toast.makeText(WormOutcoming.this, "保存失败", Toast.LENGTH_SHORT).show();
                        }
                    }) {
                        @Override
                        protected Map<String, String> getParams() throws AuthFailureError {
                            Map<String, String> map=new HashMap<>();
                            map.put("dischargeDate", outcoming_date.getText().toString());
                            map.put("cabinetNumber", cabinetNumber.getText().toString());
                            map.put("layerNumber",  layerNumber.getText().toString());
                            map.put("factory",factory);
                            return map;
                        }
                    };
                    stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                            DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
                    queue.add(stringRequest);
                })
                .show();
    }
    //                    修改进料日期
    public void changeDate(final TextView tv_out, final TextView tv_in,Calendar calendar,SimpleDateFormat simpleDateFormat){
        try {
            calendar.setTime(simpleDateFormat.parse(tv_out.getText().toString()));
            Date incomeDate = new Date(calendar.getTimeInMillis()-604800000L);
            tv_in.setText(simpleDateFormat.format(incomeDate));
            getdis();
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
    //    获取出料柜号层数
    private void getdis() {
        //提交请求
        RequestQueue queue = Volley.newRequestQueue(this);
        String url = Config.url + "/kitchenwaste/discharge/getdis?factory=" + factory+"&dischargeDate="+outcoming_date.getText().toString();
        StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        Log.d("jy",response.toString());
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            JSONObject data = jsonObject.getJSONObject("data");
                            if(data!=null && !data.isNull("id")){
                                recordid=data.getString("id");
                                cabinetNumber.setText(data.getString("cabinetNumber"));
                                layerNumber.setText(data.getString("layerNumber"));
                                if(data.getString("insectDungWeight") != null &&data.getString("insectWeight") != null&& (!data.getString("insectDungWeight").equals("null")) &&(!data.getString("insectWeight").equals("null"))){
                                    worm_outcoming_insectDung.setText(data.getString("insectDungWeight"));
                                    worm_outcoming_insect.setText(data.getString("insectWeight"));
                                }else{
                                    worm_outcoming_insectDung.setText("");
                                    worm_outcoming_insect.setText("");
                                }
                            }
                        } catch (JSONException e) {
//                            清空
                            recordid=null;
                            cabinetNumber.setText("");
                            layerNumber.setText("");
                            worm_outcoming_insectDung.setText("");
                            worm_outcoming_insect.setText("");
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                recordid=null;
            }
        });
        stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        queue.add(stringRequest);
    }

}
